package com.ruoyi.web.controller.system;


import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.DtMembers;
import com.ruoyi.system.domain.DtQuestion;
import com.ruoyi.system.service.IDtMembersService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 党员实有Controller
 * 
 * @author ruoyi
 * @date 2024-03-22
 */
@RestController
@RequestMapping("/system/members")
public class DtMembersController extends BaseController
{
    @Autowired
    private IDtMembersService dtMembersService;

    /**
     * 查询党员实有列表
     */
    @PreAuthorize("@ss.hasPermi('system:members:list')")
    @GetMapping("/list")
    public TableDataInfo list(DtMembers dtMembers)
    {
        startPage();
        List<DtMembers> list = dtMembersService.selectDtMembersList(dtMembers);
        return getDataTable(list);
    }

    /**
     * 导出党员实有列表
     */
    @PreAuthorize("@ss.hasPermi('system:members:export')")
    @Log(title = "党员实有", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DtMembers dtMembers)
    {
        List<DtMembers> list = dtMembersService.selectDtMembersList(dtMembers);
        ExcelUtil<DtMembers> util = new ExcelUtil<DtMembers>(DtMembers.class);
        util.exportExcel(response, list, "党员实有数据");
    }

    /**
     * 获取党员实有详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:members:query')")
    @GetMapping(value = "/{name}")
    public AjaxResult getInfo(@PathVariable("name") String name)
    {
        return success(dtMembersService.selectDtMembersByName(name));
    }

    /**
     * 新增党员实有
     */
    @PreAuthorize("@ss.hasPermi('system:members:add')")
    @Log(title = "党员实有", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DtMembers dtMembers)
    {
        return toAjax(dtMembersService.insertDtMembers(dtMembers));
    }

    /**
     * 修改党员实有
     */
    @PreAuthorize("@ss.hasPermi('system:members:edit')")
    @Log(title = "党员实有", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DtMembers dtMembers)
    {
        return toAjax(dtMembersService.updateDtMembers(dtMembers));
    }

    /**
     * 删除党员实有
     */
    @PreAuthorize("@ss.hasPermi('system:members:remove')")
    @Log(title = "党员实有", businessType = BusinessType.DELETE)
	@DeleteMapping("/{names}")
    public AjaxResult remove(@PathVariable String[] names)
    {
        return toAjax(dtMembersService.deleteDtMembersByNames(names));
    }
    
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        //List<DtQuestion> questionList = new ArrayList<>();
    	int successCount = 0;
    	int failCount = 0;
    	int i = 0 ;
        try(Workbook workbook = WorkbookFactory.create(file.getInputStream())) {
            //Workbook workbook = WorkbookFactory.create(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(0); // 假设Excel中只有一个Sheet
         // 获取DtQuestion类的Class对象
            Class<DtMembers> clazz = DtMembers.class;

            // 从第二行开始遍历Excel文件，跳过表头
            for (i = 1; i <= sheet.getLastRowNum(); i++) {
            	
            	int result;
                Row row = sheet.getRow(i);
                DtMembers data = clazz.newInstance();

                // 根据列数给实体类赋值
                Cell cell1 = row.getCell(0);
                data.setName(cellValue(cell1));
                
                Cell cell2 = row.getCell(1);
                data.setGender(cellValue(cell2));

                Cell cell3 = row.getCell(2);
                data.setZuzhi(cellValue(cell3));

                Cell cell4 = row.getCell(3);
                data.setCode(cellValue(cell4));
                
                result = dtMembersService.insertDtMembers(data);
                
                if(result == 1 ) {
                	successCount += 1;
                }else if (result == 0) {
                	failCount += 1;
                }else {}
            }
            
        } catch (Exception e) {
            // 处理异常
        	e.printStackTrace();
        }
        return success("共导入了" + (i-1) + "条数据，其中" + successCount + "条成功，" + ((i-1)-successCount) + "条失败");
    }
    
    private String cellValue(Cell cell) {
        String cellValue = null;
        System.out.println("cell内容为：" + cell);
        System.out.println(cell.getCellType());
        if (cell.getCellType() == CellType.STRING) {
            cellValue = cell.getStringCellValue();
        } else if (cell.getCellType() == CellType.NUMERIC) {
            if (DateUtil.isCellDateFormatted(cell)) {
                cellValue = new SimpleDateFormat("yyyy-MM-dd").format(cell.getDateCellValue());
            } else {
                cellValue = String.valueOf(cell.getNumericCellValue());
            }
        } else {
            // 其他情况的处理
        }
        return cellValue;
    }
}
